package com.xgq.drink.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xgq.drink.annotation.RequiresRole;
import com.xgq.drink.entity.R;
import com.xgq.drink.entity.Brand;
import com.xgq.drink.entity.User;
import com.xgq.drink.mapper.BrandMapper;
import com.xgq.drink.service.IBrandService;
import com.xgq.drink.service.IUserService;
import com.xgq.drink.utils.JwtTokenUtil;
import com.xgq.drink.utils.RUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/api/brand")
@Tag(name = "品牌模块", description = "品牌相关接口")
public class BrandController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private IUserService userService;
    @Autowired
    private IBrandService brandService;
    @Autowired
    private BrandMapper brandMapper;

    @PostMapping("/create")
    @Operation(summary = "创建品牌", description = "创建一个新的品牌")
    public R createBrand(@RequestBody Brand brand) {
        // 用户ID会从token中自动获取
        return brandService.createBrand(brand);
    }

    @PutMapping("/updateBrand")
    @RequiresRole(value = {"STORE_STAFF","STORE_OWNER"}, brandRequired = true)
    @Operation(summary = "更新品牌信息", description = "更新指定品牌的信息，需要STORE_STAFF角色权限")
    public R updateBrand(@RequestBody Brand brand, HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        Long brandId = jwtTokenUtil.getStoreIdFromToken(token);
        // 只允许修改指定字段
        Brand updateParams = new Brand();
        updateParams.setBrandId(brandId);
        updateParams.setBrandName(brand.getBrandName());
        updateParams.setBrandLogoUrl(brand.getBrandLogoUrl());
        updateParams.setBrandDescription(brand.getBrandDescription());
        updateParams.setBackgroundImageUrl(brand.getBackgroundImageUrl());
        return brandService.updateBrand(updateParams);
    }

    @GetMapping("/{brandId}/info")
    @Operation(summary = "获取品牌信息", description = "获取指定品牌的详细信息")
    @Parameter(name = "brandId", description = "品牌ID", required = true)
    public R getBrandInfo(@PathVariable Long brandId) {
        if (brandId == null) {
            return RUtils.fail("品牌ID不能为空");
        }
        Brand brand = brandService.getBrandInfo(brandId);
        return brand != null ? RUtils.success("获取品牌信息成功", brand) : RUtils.fail("品牌不存在");
    }
    @PostMapping("/settleIn")
    @Operation(summary = "商家入驻申请")
    public R settleIn(@RequestBody Brand brand, HttpServletRequest request) {
        // 从token获取申请用户ID
        String token = request.getHeader("Authorization");
        Long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));

        // 验证必要字段
        if (StringUtils.isBlank(brand.getBrandName()) ||
                StringUtils.isBlank(brand.getBrandLogoUrl()) ||
                StringUtils.isBlank(brand.getBrandDescription())) {
            return RUtils.fail("品牌名称、Logo和描述为必填项");
        }

        // 设置初始状态（根据Brand实体中的@TableLogic逻辑删除字段）
        brand.setIsDeleted(0); // 0表示未删除/有效状态
        brand.setCreatedAt(LocalDateTime.now());

        // 调用服务层处理
        return brandService.handleSettleIn(brand, userId);
    }
    /**
     * 删除品牌（逻辑删除）
     */
    @DeleteMapping("/delete/{brandId}")
    @RequiresRole("STORE_OWNER")
    @Operation(summary = "删除品牌", description = "逻辑删除指定的品牌，需要STORE_OWNER角色权限")
    @Parameter(name = "brandId", description = "品牌ID", required = true)
    public R deleteBrand(@PathVariable Long brandId) {
        if (brandId == null) {
            return RUtils.fail("品牌ID不能为空");
        }
        boolean deleted = brandService.removeById(brandId);
        return deleted ? RUtils.success("品牌删除成功") : RUtils.fail("品牌删除失败");
    }
    @PutMapping("/toggleStatus/{brandId}")
    @RequiresRole("ADMIN")
    @Operation(summary = "禁用/启用商家", description = "管理员操作商家状态")
    public R toggleBrandStatus(@PathVariable Long brandId, @RequestParam boolean isDisabled) {
        try {
            if (brandMapper.updateDisplayStatus(brandId,isDisabled ? 1 : 0)){
                return RUtils.success(isDisabled ? "商家已禁用" : "商家已启用");
            }else {
                return RUtils.fail("操作失败");
            }

        } catch (Exception e) {
            return RUtils.fail("操作失败: " + e.getMessage());
        }
    }

    /**
     * 查询所有品牌
     */
    @RequiresRole("ADMIN")
    @GetMapping("/list")
    @Operation(summary = "获取所有品牌", description = "获取系统中所有未删除的品牌列表")
    public List<Brand> getAllBrands() {
        return brandMapper.selectBrandAll();
    }

    /**
     * 查询店铺下的商品列表
     */
    @GetMapping("/{brandId}/products")
    @Operation(summary = "获取品牌商品列表", description = "获取指定品牌下的所有商品列表，无需特殊权限")
    @Parameter(name = "brandId", description = "品牌ID", required = true)
    public R getBrandProducts(@PathVariable Long brandId) {
        if (brandId == null) {
            return RUtils.fail("品牌ID不能为空");
        }
        return brandService.getBrandProducts(brandId);
    }
}